//	饼图自定义配色

import React, { useEffect, useState } from 'react';
import InputColorPicker from './InputColorPicker';
import FormItem from 'antd/lib/form/FormItem';
import { filterObjectNullKeys } from 'src/libs/utils';

interface IProps {
	config: any;
	onValuesChange: ( chartType: string, key: string, values: Object, configType: string ) => void;
	form: any;
}

interface customColorType {
	item: string;
	color: string;
}

const QuotaCustomColor = ( props: IProps ) => {
	let { config, form, onValuesChange } = props;
	const [ chartCustomBlockColor, setChartCustomBlockColor ] = useState( ( config.style && config.style.customBlockColor ) || [] );

	const handleQuotaColorChange = ( itemName, color ) => {
		const array = Array.from( config.style.customBlockColor );
		const index = array.findIndex( ( v: customColorType ) => v.item === itemName );
		array.splice( index, 1, { item: itemName, color: color } );

		setChartCustomBlockColor( array );
		form.setFieldsValue( { customBlockColor: array } );
		onValuesChange( config.type, config.key, filterObjectNullKeys( form.getFieldsValue() ), 'style' );
	};

	useEffect( () => {
		setChartCustomBlockColor( config.style.customBlockColor || [] );
	}, [ setChartCustomBlockColor, config.style.customBlockColor ] );

	return (
		<div>
			<FormItem
				label="指标背景颜色" name="customBlockColor" labelAlign="left" labelCol={ { span: 8 } }
				wrapperCol={ { span: 16 } }>
				{
					chartCustomBlockColor.map( ( v, i ) => {
						return (
							<div key={ i }>
								<span>{ v.item }</span>
								<InputColorPicker
									color={ v.color }
									change={ ( color ) => handleQuotaColorChange( v.item, color ) }
								></InputColorPicker>
							</div>

						);
					} )
				}
			</FormItem>


		</div>
	);
};

export default React.memo( QuotaCustomColor );
